<template>
  <div id="mine-orders">
    <navbar v-model="selected">
      <tab-item
        v-for="(item, index) in headers"
        :key="index"
        :id="item.tag">{{ item.name }}
      </tab-item>
    </navbar>

    <div
      class="orders-wrap"
      v-set-height
      v-infinite-scroll="loadMore"
      infinite-scroll-disabled="loading"
      :infinite-scroll-distance="0">
      <section
        v-for="(item, index) in orders[selected]"
        :key="index"
        @click="go(+item.status, item.company_id, item.id)">
        <header>
          <span :class="{'tip': !item.apply_policy_no}">{{ item.apply_policy_no ? '保单号：' + item.apply_policy_no : '未出单' }}</span>
          <span v-text="getStatusText(item.status)"></span>
        </header>
        <article>
          <div
            class="left"
            :class="{
                   'ha': item.company_id === '1',
                 'astp': item.company_id === '2',
                   'dh': item.company_id === '3',
                   'rb': item.company_id === '4',
                  'bbw': item.company_id === '5',
                 'tips': !item.company_id
                  }"></div>
          <div class="middle">
            <p>{{ item.plate_num || '未上牌' }}</p>
            <p>{{ item.name }}</p>
          </div>
          <div class="right">
            <p>{{ item.actual_price ? item.actual_price + '元' : '' }}</p>
            <p>{{ packages[item.package_id - 1] || '未确定险种' }}</p>
          </div>
        </article>
        <footer v-show="selected !== 'pending'"
                :class="{'normal': getStatusText(item.status) !== '待支付', 'about-code': getStatusText(item.status) === '待支付'}">
          <template v-if="getStatusText(item.status) !== '待支付'">
            <span></span>
            <section>
              <p>{{ item.start_time ? item.start_time : '待定' }}</p>
              <p>起保日期</p>
            </section>
            <section>
              <p>{{ item.end_time ? item.end_time : '待定' }}</p>
              <p>终保日期</p>
            </section>
            <section>
              <p>{{ item.insurance_period ? item.insurance_period + '天' : '待定' }}</p>
              <p>保险期限</p>
            </section>

            <span></span>
            <section>
              <p>{{ item.jq_start_time ? item.jq_start_time : '待定' }}</p>
              <p>起保日期</p>
            </section>
            <section>
              <p>{{ item.jq_end_time ? item.jq_end_time : '待定' }}</p>
              <p>终保日期</p>
            </section>
            <section>
              <p>{{ item.jq_insurance_period ? item.jq_insurance_period + '天' : '待定' }}</p>
              <p>保险期限</p>
            </section>
          </template>
          <template v-else-if="getStatusText(item.status) === '待支付'">
            <p>支付截止日期：{{ item.deadline }}</p>
            <button @click="getCode(item.id, item.company_id)"
                    :disabled="allDisabled || new Date(item.deadline + ' 24:00:00') < new Date()">二维码
            </button>
          </template>
        </footer>
        <div class="public-btn-box min-box pl-1 pr-1 mt-1">
          <button
            v-if="item.order_pay_id && getStatusText(item.status) === '待支付'"
            class="submit min"
            @click.stop="refreshOrder(item.id, item.order_pay_id, item.company_id)">状态刷新
          </button>
          <button class="warn min" @click.stop="delOrder(item.id, item.in_id)">删除订单</button>
        </div>
      </section>

      <empty-message v-show="!loading && noMore" message="已无更多"></empty-message>

      <spinner
        v-show="!noMore && loading"
        type="triple-bounce"
        color="#0196ff"
        :size="48"
        class="spinner"></spinner>
    </div>
  </div>
</template>

<script>
  import {Navbar, TabItem, Indicator, Toast, InfiniteScroll, Spinner, MessageBox} from 'mint-ui';
  import EmptyMessage from '../comp/empty-message.vue';

  export default {
    name: "mine-orders",
    components: {
      Navbar,
      TabItem,
      Spinner,
      EmptyMessage
    },
    directives: {
      'set-height': {
        inserted(el) {

          // tab-height

          let height = window.screen.availHeight - 36;
          el.style.height = height + 'px';
        }
      },
      InfiniteScroll: InfiniteScroll
    },
    data() {
      return {
        headers: [
          {
            name: '全部',
            tag: 'all'
          },
          {
            name: '到期',
            tag: 'overdue'
          },
          {
            name: '待处理',
            tag: 'pending'
          },
          {
            name: '待核对',
            tag: 'checking'
          },
          {
            name: '待支付',
            tag: 'paying'
          },
          {
            name: '已完成',
            tag: 'finished'
          }
        ],
        orders: {
          all: [],
          overdue: [],
          pending: [],
          checking: [],
          paying: [],
          finished: []
        },
        ordersDB: {
          all: [],
          overdue: [],
          pending: [],
          checking: [],
          paying: [],
          finished: []
        },
        packages: [
          '经济型',
          '全面型',
          '豪华型',
          '自定义'
        ],
        selected: this.$route.query.type,
        allDisabled: false,
        loading: true,
        noMore: false
      }
    },
    methods: {
      getCode(order_id, company_id) {

        this.allDisabled = true;
        Indicator.open({
          text: '二维码生成中',
          spinnerType: 'snake'
        });

        this.$http.post({
          api: this.$api.INSURANCE_POLICY_CONFIRM_AGAIN,
          params: {
            order_id: order_id,
            company_id: company_id
          },

          // 支付二维码

          success: (res) => {
            Indicator.close();
            this.$router.push({
              name: 'PayInsuranceFinal',
              params: {
                company_id: company_id,
                order_id: order_id,
                order_pay_id: res.data.msg.qrcode.order_pay_id
              },
              query: {
                num: res.data.msg.people.plate_num,
                price: res.data.msg.price,
                code: res.data.msg.qrcode.url
              }
            })
          },

          // 获取失败

          failure: () => {
            Indicator.close();
            Toast('获取失败');
            this.allDisabled = false;
          },

          error: () => {
            Indicator.close();
            Toast('网络错误，或已过期');
            this.allDisabled = false;
          }
        })
      },
      go(status, company_id, order_id) {

        if (status === 98) {
          this.$router.push({
            name: 'MineOrderPending',
            params: {
              order_id: order_id,
              status: 3
            }
          });
        }

        if (status === 0 || status === 99 || status === 5 || status === 7) {
          this.$router.push({
            path: '/tip/1',
            query: {
              company_id: company_id,
              order_id: order_id
            }
          });
        }

        if (status === 4 || status === 3 || status === 2) {
          this.$router.push({
            name: 'MineOrderDetail',
            params: {
              order_id: order_id,
              status: 6
            }
          });
        }
      },
      loadMore() {
        if (this.noMore) {
          return;
        }

        this.loading = true;
        setTimeout(() => {
          this.orders[this.selected] = this.orders[this.selected].concat(this.ordersDB[this.selected].splice(0, 5));

          this.loading = false;
          this.noMore = !this.ordersDB[this.selected].length;
        }, 2000);
      },
      selectedChange() {

        // 初始化

        if (!this.orders[this.selected].length) {
          this.orders[this.selected] = this.orders[this.selected].concat(this.ordersDB[this.selected].splice(0, 5));
        }

        if (!this.loading) {
          this.noMore = !this.ordersDB[this.selected].length;
        }

        document.getElementsByClassName('orders-wrap')[0].scrollTop = 0;

      },
      getStatusText(status) {
        switch (+status) {
          case 97:
            // 1. 到期
            return '到期';

          case 98:
            // 2. 待处理
            return '待处理';

          case 0:
            // 3.1 待核对
            return '待核对';
          case 99:
            // 3.2 待核对
            return '待核对';
          case 5:
            // 3.3 待核对
            return '待核对';
          case 7:
            // 3.4 待核对
            return '待核对';

          case 1:
            // 4. 待支付
            return '待支付';

          case 4:
            // 5.1 已完成
            return '已完成';
          case 3:
            // 5.2 已完成
            return '已完成';
          case 2:
            // 5.3 已完成
            return '已完成';
          default:
            return '无效订单';
        }
      },
      delOrder(id, in_id) {
        MessageBox.confirm('确定删除此订单?').then(action => {
          if (action === 'confirm') {
            let _this = this;
            this.$http.post({
              api: this.$api.USER_ORDERS_DELETE,
              params: in_id ?
                {
                  in_id: in_id
                } :
                {
                  order_id: id
                },
              success(res) {
                Toast(res.data.msg);
                // 初始化
                _this.init();
              }
            });
          }
        });
      },
      init() {
        this.orders = {
          all: [],
          overdue: [],
          pending: [],
          checking: [],
          paying: [],
          finished: []
        };
        this.ordersDB = {
          all: [],
          overdue: [],
          pending: [],
          checking: [],
          paying: [],
          finished: []
        };

        this.loading = true;
        this.$http.post({
          api: this.$api.USER_ORDERS,
          params: {
            user_id: localStorage.getItem('id'),
            status: 1
          },
          success: (res) => {
            this.ordersDB.all = res.data.data;

            for (let i = 0; i < this.ordersDB.all.length; i++) {
              switch (+this.ordersDB.all[i].status) {
                case 97:
                  // 1. 到期
                  this.ordersDB.overdue.push(this.ordersDB.all[i]);
                  break;

                case 98:
                  // 2. 待处理
                  this.ordersDB.pending.push(this.ordersDB.all[i]);
                  break;

                case 0:
                  // 3.1 待核对
                  this.ordersDB.checking.push(this.ordersDB.all[i]);
                  break;
                case 99:
                  // 3.2 待核对
                  this.ordersDB.checking.push(this.ordersDB.all[i]);
                  break;
                case 5:
                  // 3.3 待核对
                  this.ordersDB.checking.push(this.ordersDB.all[i]);
                  break;
                case 7:
                  // 3.4 待核对
                  this.ordersDB.checking.push(this.ordersDB.all[i]);
                  break;

                case 1:
                  // 4. 待支付
                  this.ordersDB.paying.push(this.ordersDB.all[i]);
                  break;

                case 4:
                  // 5.1 已完成
                  this.ordersDB.finished.push(this.ordersDB.all[i]);
                  break;
                case 3:
                  // 5.2 已完成
                  this.ordersDB.finished.push(this.ordersDB.all[i]);
                  break;
                case 2:
                  // 5.3 已完成
                  this.ordersDB.finished.push(this.ordersDB.all[i]);
                  break;
                default:
                  break;
              }
            }

            this.loading = false;
            this.noMore = !this.ordersDB[this.selected].length;
          }
        });
      },
      refreshOrder(id, payId, companyId) {
        let _this = this;
        this.$http.post({
          api: this.$api.INSURANCE_PAY_CONFIRM,
          params: {
            company_id: companyId,
            order_id: id,
            order_pay_id: payId
          },
          success(res) {
            MessageBox.alert(res.data.msg).then(action => {
              if (action === 'confirm') {
                // 初始化
                _this.init();
              }
            });
          }
        });
      }
    },
    created() {
      this.init();
    },
    watch: {
      selected: 'selectedChange'
    }
  }
</script>

<style lang="scss">

  #mine-orders {

    $tab-height: 36px;

    padding-top: $tab-height;

    > .mint-navbar {
      position: fixed;
      top: 0;
      left: 0;
      display: flex;
      align-items: center;
      width: $size-as-parent;
      padding: 0 .6rem;

      > .mint-tab-item {
        display: flex;
        justify-content: space-around;
        align-items: center;
        height: $tab-height;
        padding: 0;
        color: #333;

        > .mint-tab-item-label {
          font-size: 1.5rem;
        }
      }
    }

    > .orders-wrap {
      padding-top: 10px;
      overflow: scroll;
      -webkit-overflow-scrolling: touch;

      > section {

        $this-public-padding: 0 1rem;

        margin-bottom: 1rem;
        background: $white;
        border-radius: 1.8rem;
        box-shadow: $public-box-shadow;

        > header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          height: 3.5rem;
          padding: $this-public-padding;
          border-bottom: 1px solid #f5f5f5;

          > span:first-of-type {
            font-size: 1.2rem;
            color: #333;

            &.tip {
              color: #f00;
            }
          }

          > span:last-of-type {
            font-size: 1.5rem;
            color: #0196ff;
          }
        }

        > article {

          $p-mb: 1.2rem;

          display: flex;
          align-items: center;
          height: 8rem;
          padding: $this-public-padding;
          font-size: 1.5rem;
          border-bottom: 1px solid #f5f5f5;

          > .left {
            width: 70px;
            height: 54px;
            margin: 0 1.8rem 0 .8rem;

            &.tips {
              background: url("../../assets/images/public/not-chose-yet.png") no-repeat center / $size-as-parent auto;
            }

            &.ha {
              background: url("../../assets/images/public/companies-2.png") no-repeat (center top) / $size-as-parent auto;
            }

            &.astp {
              background: url("../../assets/images/public/companies-2.png") no-repeat (center -97px) / $size-as-parent auto;
            }

            &.dh {
              background: url("../../assets/images/public/companies-2.png") no-repeat (center -204px) / $size-as-parent auto;
            }

            &.rb {
              background: url("../../assets/images/public/companies-2.png") no-repeat (center -301px) / $size-as-parent auto;
            }

            &.bbw {
              background: url("../../assets/images/public/companies-2.png") no-repeat (center -379px) / $size-as-parent auto;
            }
          }

          > .middle {
            flex: 1;

            > p:first-of-type {
              margin-bottom: $p-mb;
              font-weight: bold;
              color: #0196ff;
            }

            > p:last-of-type {
              color: #333;
            }
          }

          > .right {
            text-align: right;

            > p:first-of-type {
              margin-bottom: $p-mb;
              color: #f00;
            }

            > p:last-of-type {
              color: #999;
            }
          }
        }

        > footer {
          display: flex;
          align-items: center;
          padding: $this-public-padding;
          border-bottom: 1px solid #f5f5f5;

          &.normal {
            flex-wrap: wrap;
            height: 12.4rem;
            justify-content: space-around;

            > section {
              width: 31%;
              text-align: center;

              > p:first-of-type {
                margin-bottom: 1.2rem;
              }

              > p:last-of-type {
                font-size: 1.5rem;
                color: #999;
              }
            }

            > span {
              width: 7%;
              height: 0;
              padding-bottom: 7%;
              background: url("../../assets/images/mine/icon-insurance-type.png") no-repeat (0 0) / $size-as-parent auto;

              &:first-of-type {
                background-position: 0 0;
              }

              &:last-of-type {
                background-position: 0 bottom;
              }
            }
          }

          &.about-code {
            height: 4rem;
            justify-content: space-between;

            > p {
              font-size: 1.2rem;
              color: #f00;
            }

            > button {
              width: 8rem;
              height: 2.5rem;
              font-size: 1.5rem;
              color: $white;
              border-radius: .6rem;
              background: #0097ff;

              &[disabled] {
                background: #bbb;
              }
            }
          }
        }
      }

      > p {
        text-align: center;
      }

      > .spinner {
        display: flex;
        justify-content: space-around;
        margin: .8rem 0;
      }
    }
  }
</style>
